<template>
  <div class="app-container">

    <!-- 搜索表单 -->
    <el-form :inline="true" class="mb-4">
      <el-form-item label="商品ID">
        <el-input
          v-model="queryParams.item_id"
          placeholder="请输入商品ID"
          clearable
          style="width: 200px"
        />
      </el-form-item>
      <el-form-item label="商品标题">
        <el-input
          v-model="queryParams.item_title"
          placeholder="请输入商品标题"
          clearable
          style="width: 200px"
        />
      </el-form-item>
      <el-form-item label="搜索关键词">
        <el-input
          v-model="queryParams.keyword"
          placeholder="请输入搜索关键词"
          clearable
          style="width: 200px"
        />
      </el-form-item>
      <el-form-item label="客户端">
        <el-select
          v-model="queryParams.client_id"
          placeholder="请选择客户端"
          clearable
          style="width: 200px"
        >
          <el-option label="所有客户端" value="" />
          <el-option
            v-for="client in clientOptions"
            :key="client.client_id"
            :label="client.display"
            :value="client.client_id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="订单状态">
        <el-select
          v-model="queryParams.order_status"
          placeholder="请选择状态"
          clearable
          style="width: 150px"
        >
          <el-option label="待支付" value="pending" />
          <el-option label="成功" value="success" />
          <el-option label="失败" value="failed" />
          <el-option label="已取消" value="cancelled" />
        </el-select>
      </el-form-item>
      <el-form-item label="卖家ID">
        <el-input
          v-model="queryParams.seller_id"
          placeholder="请输入卖家ID"
          clearable
          style="width: 200px"
        />
      </el-form-item>
      <el-form-item label="下单时间">
        <el-date-picker
          v-model="dateRange"
          type="datetimerange"
          range-separator="-"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
          style="width: 350px"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="handleReset">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 工具栏 -->
    <el-row :gutter="10" class="mb-4">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Refresh" @click="loadOrderList">刷新</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleExport">导出</el-button>
      </el-col>
    </el-row>

    <!-- 统计卡片 -->
    <el-row :gutter="20" class="mb-4">
      <el-col :span="6">
        <el-card shadow="hover">
          <template #header>
            <span>今日下单</span>
          </template>
          <div style="text-align: center; font-size: 24px; color: #409EFF">
            <strong>{{ todayOrderCount }}</strong> 单
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover">
          <template #header>
            <span>成功订单</span>
          </template>
          <div style="text-align: center; font-size: 24px; color: #67C23A">
            <strong>{{ successOrderCount }}</strong> 单
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover">
          <template #header>
            <span>失败订单</span>
          </template>
          <div style="text-align: center; font-size: 24px; color: #F56C6C">
            <strong>{{ failedOrderCount }}</strong> 单
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover">
          <template #header>
            <span>总金额</span>
          </template>
          <div style="text-align: center; font-size: 24px; color: #E6A23C">
            <strong>¥{{ totalAmount }}</strong>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 订单列表表格 -->
    <el-table
      :data="orderList"
      border
      v-loading="loading"
    >
      <el-table-column label="序号" type="index" width="60" align="center" />
      <el-table-column label="商品图片" width="100" align="center">
        <template #default="{ row }">
          <div 
            v-if="row.pic_url"
            @click="handleImagePreview(row)"
            style="width: 70px; height: 70px; border-radius: 4px; cursor: pointer; overflow: hidden; position: relative;"
          >
            <el-image
              :src="row.pic_url"
              fit="cover"
              style="width: 100%; height: 100%;"
              :preview-src-list="[]"
              :hide-on-click-modal="true"
            />
          </div>
          <span v-else style="color: #C0C4CC;">-</span>
        </template>
      </el-table-column>
      <el-table-column label="商品ID" prop="item_id" align="center" width="120" />
      <el-table-column label="商品标题" prop="item_title" align="center" min-width="200" show-overflow-tooltip />
      <el-table-column label="商品价格" prop="item_price" align="center" width="100">
        <template #default="{ row }">
          <span style="color: #E6A23C; font-weight: bold">¥{{ row.item_price || '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="下单方式" prop="is_auto_order" align="center" width="100">
        <template #default="{ row }">
          <el-tag :type="row.is_auto_order ? 'success' : 'info'">
            {{ row.is_auto_order ? '自动下单' : '手动下单' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="客户端" prop="client_name" align="center" width="150">
        <template #default="{ row }">
          <div>
            <div style="font-weight: 500;">
              {{ row.client_name || '-' }}
              <span v-if="row.client_remark" style="color: #909399; font-weight: normal;">({{ row.client_remark }})</span>
            </div>
            <div style="font-size: 12px; color: #909399;">{{ row.client_id || '-' }}</div>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="订单状态" prop="order_status" align="center" width="100">
        <template #default="{ row }">
          <el-tag :type="getStatusType(row.order_status)">
            {{ getStatusLabel(row.order_status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="错误信息" prop="error_msg" align="center" min-width="150" show-overflow-tooltip>
        <template #default="{ row }">
          <span v-if="row.error_msg" style="color: #F56C6C;">{{ row.error_msg }}</span>
          <span v-else style="color: #C0C4CC;">-</span>
        </template>
      </el-table-column>
      <el-table-column label="下单时间" prop="order_time" align="center" width="160">
        <template #default="{ row }">
          {{ formatDateTime(row.order_time) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="300" fixed="right">
        <template #default="{ row }">
          <el-button 
            link 
            type="primary" 
            icon="ChatDotRound" 
            @click="handleChat(row)"
            v-if="row.seller_id"
          >
            对话
          </el-button>
          <el-button 
            link 
            type="primary" 
            icon="Wallet" 
            @click="handlePayOrder(row)"
            :disabled="!row.pay_url || (row.order_status !== 'ordered' && row.order_status !== 'paid')"
            v-if="row.pay_url && (row.order_status === 'ordered' || row.order_status === 'paid')"
          >
            支付
          </el-button>
          <!-- ✅ 修复：ordered、paid、success状态都可以取消 -->
          <el-button 
            link 
            type="warning" 
            icon="CloseBold" 
            @click="handleCancelOrder(row)"
            v-if="row.order_status === 'ordered' || row.order_status === 'paid' || row.order_status === 'success'"
          >
            取消订单
          </el-button>
          <el-button 
            link 
            type="danger" 
            icon="Delete" 
            @click="handleDeleteOrder(row)"
          >
            删除
          </el-button>
          <span v-if="!row.pay_url && row.order_status !== 'ordered' && row.order_status !== 'paid' && row.order_status !== 'success'" style="color: #C0C4CC;">-</span>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
      class="mt-4"
      v-model:current-page="queryParams.pageNum"
      v-model:page-size="queryParams.pageSize"
      :page-sizes="[10, 20, 50, 100]"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handlePageChange"
      @current-change="handlePageChange"
    />

    <!-- 取消订单弹窗 -->
    <el-dialog
      v-model="cancelDialogVisible"
      title="取消订单"
      width="400px"
      :close-on-click-modal="false"
    >
      <el-form :model="cancelForm" label-width="100px">
        <el-form-item label="订单记录ID">
          <span>{{ cancelForm.order_record_id }}</span>
        </el-form-item>
        <el-form-item label="取消理由">
          <el-select v-model="cancelForm.reason" placeholder="请选择取消理由" style="width: 100%">
            <el-option label="不想买了" value="不想买了" />
            <el-option label="信息填写错误，重新下单" value="信息填写错误，重新下单" />
            <el-option label="同城见面交易" value="同城见面交易" />
            <el-option label="其他原因" value="其他原因" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="cancelDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitCancelOrder">确定</el-button>
      </template>
    </el-dialog>

    <!-- 图片预览弹窗 -->
    <el-dialog
      v-model="previewImageVisible"
      :title="previewImageTitle"
      width="600px"
      :close-on-click-modal="true"
    >
      <div style="text-align: center;">
        <el-image
          :src="previewImageUrl"
          fit="contain"
          style="max-width: 100%; max-height: 500px;"
        />
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, onUnmounted } from 'vue'
import { ElMessage, ElMessageBox, ElNotification } from 'element-plus'
import { cancelOrder, getOrderList, deleteOrder, getAgentClientList } from '@/api/agent'
import { openChat } from '@/api/chat'
import { websocketManager } from '@/utils/websocket'
import useChatStore from '@/store/modules/chat'
import { useAgentStore } from '@/store/modules/agent'

const loading = ref(false)
const total = ref(0)
const orderList = ref([])
const dateRange = ref([])
const clientOptions = ref([])

const queryParams = reactive({
  item_id: '',
  item_title: '',
  keyword: '',
  client_id: '',
  order_status: '',
  seller_id: '',
  pageNum: 1,
  pageSize: 10
})

// 取消订单
const cancelDialogVisible = ref(false)
const cancelForm = reactive({
  order_record_id: null,  // ✅ 修复：使用订单记录ID
  reason: '不想买了'
})

// 图片预览
const previewImageUrl = ref('')
const previewImageTitle = ref('')
const previewImageVisible = ref(false)

// 统计数据
const todayOrderCount = computed(() => {
  const today = new Date().toDateString()
  return orderList.value.filter(order => {
    if (!order.order_time) return false
    return new Date(order.order_time).toDateString() === today
  }).length
})

const successOrderCount = computed(() => {
  // 成功订单：已支付（paid）或成功（success）
  return orderList.value.filter(order => 
    order.order_status === 'paid' || order.order_status === 'success'
  ).length
})

const failedOrderCount = computed(() => {
  return orderList.value.filter(order => order.order_status === 'failed').length
})

const totalAmount = computed(() => {
  // 计算已支付（paid）或成功（success）的订单金额
  return orderList.value
    .filter(order => 
      (order.order_status === 'paid' || order.order_status === 'success') && 
      order.item_price
    )
    .reduce((sum, order) => {
      const price = parseFloat(order.item_price) || 0
      return sum + price
    }, 0)
    .toFixed(2)
})

/**
 * 加载订单列表
 */
async function loadOrderList() {
  console.log('[OrderRecords] 开始加载订单列表')
  loading.value = true
  try {
    const params = {
      page_num: queryParams.pageNum,
      page_size: queryParams.pageSize
    }
    
    if (queryParams.item_id) params.item_id = queryParams.item_id
    if (queryParams.item_title) params.item_title = queryParams.item_title
    if (queryParams.keyword) params.keyword = queryParams.keyword
    if (queryParams.client_id) params.client_id = queryParams.client_id
    if (queryParams.seller_id) params.seller_id = queryParams.seller_id
    if (queryParams.order_status) params.order_status = queryParams.order_status
    
    // 时间范围过滤（如果有）
    if (dateRange.value && dateRange.value.length === 2) {
      params.start_time = toISOString(dateRange.value[0])
      params.end_time = toISOString(dateRange.value[1])
    }
    
    console.log('[OrderRecords] 请求参数:', params)
    const res = await getOrderList(params)
    console.log('[OrderRecords] API响应:', res)
    
    if (res && res.data) {
      orderList.value = res.data.rows || []
      total.value = res.data.total || 0
      console.log('[OrderRecords] 加载成功，订单数量:', orderList.value.length, '总数:', total.value)
    } else {
      console.warn('[OrderRecords] API返回数据为空或格式不正确')
      orderList.value = []
      total.value = 0
    }
  } catch (error) {
    console.error('[OrderRecords] 加载订单列表失败:', error)
    ElMessage.error('加载订单列表失败：' + (error.message || '未知错误'))
    orderList.value = []
    total.value = 0
  } finally {
    loading.value = false
    console.log('[OrderRecords] 加载完成')
  }
}

/**
 * 搜索
 */
function handleQuery() {
  queryParams.pageNum = 1
  loadOrderList()
}

/**
 * 重置
 */
function handleReset() {
  queryParams.item_id = ''
  queryParams.item_title = ''
  queryParams.keyword = ''
  queryParams.client_id = ''
  queryParams.order_status = ''
  queryParams.seller_id = ''
  dateRange.value = []
  queryParams.pageNum = 1
  loadOrderList()
}

/**
 * 导出
 */
function handleExport() {
  ElMessage.info('导出功能开发中...')
}

/**
 * 格式化日期时间
 */
function formatDateTime(datetime) {
  if (!datetime) return '-'
  const date = new Date(datetime)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  })
}

/**
 * 获取状态标签类型
 */
function getStatusType(status) {
  const map = {
    'pending': 'warning',
    'ordered': 'warning',  // 已下单待支付
    'paid': 'success',     // 已支付
    'success': 'success',
    'failed': 'danger',
    'cancelled': 'info'
  }
  return map[status] || 'info'
}

/**
 * 获取状态标签文字
 */
function getStatusLabel(status) {
  const map = {
    'pending': '待下单',
    'ordered': '待支付',   // 已下单待支付
    'paid': '已支付',      // 已支付
    'success': '成功',
    'failed': '失败',
    'cancelled': '已取消'
  }
  return map[status] || status || '-'
}

/**
 * 支付订单
 */
function handlePayOrder(row) {
  if (!row.pay_url) {
    ElMessage.warning('支付链接不存在')
    return
  }
  // 在新标签页打开支付链接
  window.open(row.pay_url, '_blank')
}

/**
 * 取消订单
 */
function handleCancelOrder(row) {
  // ✅ 检查：pending状态的订单还没有创建（没有biz_order_id），无法取消
  if (row.order_status === 'pending') {
    ElMessage.warning('订单尚未创建，无法取消')
    return
  }
  
  // ✅ 检查：已取消或已失败的订单无法取消
  if (row.order_status === 'cancelled' || row.order_status === 'failed') {
    ElMessage.warning('订单已取消或已失败，无法再次取消')
    return
  }
  
  // ✅ 检查：如果没有biz_order_id（兼容bizOrderId），提示用户
  const bizOrderId = row.biz_order_id || row.bizOrderId
  if (!bizOrderId) {
    ElMessage.warning('订单号不存在，可能已被取消，请刷新后重试')
    console.warn('订单数据:', row)
    return
  }
  
  // ✅ 修复：使用订单记录ID（参考C#代码逻辑）
  if (!row.id) {
    ElMessage.warning('无法获取订单记录ID，请稍后重试')
    return
  }
  
  cancelForm.order_record_id = row.id  // ✅ 使用订单记录ID
  cancelForm.reason = '不想买了'
  cancelDialogVisible.value = true
}

/**
 * 提交取消订单
 */
async function submitCancelOrder() {
  if (!cancelForm.reason) {
    ElMessage.warning('请选择取消理由')
    return
  }
  
  if (!cancelForm.order_record_id) {
    ElMessage.warning('订单信息不完整')
    return
  }
  
  try {
    // ✅ 修复：使用订单记录ID，而不是client_id和order_id
    const response = await cancelOrder(cancelForm.order_record_id, cancelForm.reason)
    
    if (response.code === 200) {
      ElMessage.info('取消指令已发送，正在处理中...')
      cancelDialogVisible.value = false
      // ✅ 不立即刷新列表，等待WebSocket消息返回结果后再刷新
      // 真正的取消结果会通过WebSocket实时通知并自动刷新列表
    } else {
      const errorMsg = response.msg || '取消失败'
      
      // ✅ 6. 处理订单被手机app取消的情况（订单不存在）
      if (errorMsg.includes('不存在') || errorMsg.includes('已取消') || errorMsg.toLowerCase().includes('not found')) {
        // 提示用户是否删除订单记录
        ElMessageBox.confirm(
          `订单可能已被手机app取消，是否删除订单记录？\n${errorMsg}`,
          '订单不存在',
          {
            confirmButtonText: '删除订单',
            cancelButtonText: '取消',
            type: 'warning'
          }
        ).then(() => {
          // 用户确认删除，调用删除订单API
          const orderRow = orderList.value.find(o => o.id === cancelForm.order_record_id)
          if (orderRow) {
            handleDeleteOrder(orderRow)
          }
        }).catch(() => {
          // 用户取消，不做任何操作
        })
      } else {
        ElMessage.error(errorMsg)
      }
    }
  } catch (error) {
    ElMessage.error('取消失败：' + (error.message || '未知错误'))
  }
}

/**
 * 删除订单
 */
async function handleDeleteOrder(row) {
  try {
    await ElMessageBox.confirm(
      `确定要删除订单记录 "${row.item_id}" 吗？\n此操作将从数据库直接删除记录，不可恢复！`,
      '删除订单',
      {
        confirmButtonText: '确定删除',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const response = await deleteOrder(row.id)
    
    if (response.code === 200) {
      ElNotification({
        title: '删除成功',
        message: '订单记录已删除',
        type: 'success',
        duration: 3000
      })
      // 刷新列表
      loadOrderList()
    } else {
      ElMessage.error(response.msg || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除订单失败:', error)
      ElMessage.error('删除失败：' + (error.message || '未知错误'))
    }
  }
}

// 监听分页变化
function handlePageChange() {
  loadOrderList()
}

async function loadClientOptions() {
  try {
    const { data } = await getAgentClientList({ pageNum: 1, pageSize: 500 })
    const rows = data?.rows || []
    clientOptions.value = rows.map(row => ({
      client_id: row.client_id,
      display: row.client_name || row.hostname || row.client_id
    }))
  } catch (error) {
    console.warn('[OrderRecords] 加载客户端列表失败:', error)
  }
}

function toISOString(value) {
  if (!value) return undefined
  const date = value instanceof Date ? value : new Date(value)
  if (Number.isNaN(date.getTime())) return undefined
  return date.toISOString()
}

/**
 * 图片预览
 */
function handleImagePreview(row) {
  if (row.pic_url) {
    previewImageUrl.value = row.pic_url
    previewImageTitle.value = row.item_title || '商品图片预览'
    previewImageVisible.value = true
  }
}

/**
 * WebSocket消息处理器
 */
/**
 * 打开全局聊天面板并定位到指定会话
 */
async function handleChat(row) {
  let sellerId = row.seller_id || ''
  let sellerName = row.seller_name || row.seller_nick || '未知卖家'
  const itemId = row.item_id || ''
  const itemTitle = row.item_title || row.title || ''

  if (!sellerId) {
    ElMessage.warning('缺少卖家信息，无法打开对话')
    return
  }

  // 使用全局聊天 Store
  const chatStore = useChatStore()
  const agentStore = useAgentStore()
  
  // 检查是否有在线的下单客户端
  const availableChatClients = computed(() => {
    if (!agentStore?.clients) return []
    return agentStore.clients.filter(c => 
      c.client_type === 'order' && 
      c.online_status === 'online' && 
      c.login_status === 'logged_in'
    )
  })

  if (!availableChatClients.value.length) {
    ElMessage.warning('暂无在线的下单客户端，请先启动并登录下单类型的Agent客户端')
    return
  }

  console.log('[OrderRecords] 打开对话:', { sellerId, sellerName, itemId, itemTitle })
  
  // 选择客户端（如果未选择，则使用第一个在线客户端）
  if (!chatStore.selectedClientId) {
    chatStore.selectClient(availableChatClients.value[0].client_id)
    console.log('[OrderRecords] 已选择客户端:', availableChatClients.value[0].client_id)
  }

  // 构建会话ID
  const sessionId = `${sellerId}#${itemId || ''}`
  
  // ✅ 先调用后端API创建会话记录并获取商品信息（后端使用匿名请求，避免Agent风控）
  let itemInfo = null
  let pureSellerId = sellerId // 默认使用传入的sellerId
  
  if (chatStore.selectedClientId) {
    try {
      const response = await openChat({
        client_id: chatStore.selectedClientId,
        seller_id: sellerId,
        item_id: itemId,
        seller_name: sellerName
      })
      
      console.log('[OrderRecords] openChat响应:', response)
      
      // ✅ 后端通过匿名请求获取了商品信息，直接使用
      if (response.code === 200 && response.data) {
        itemInfo = response.data
        
        // ✅ 使用后端返回的纯数字seller_id（从匿名请求获取的）
        if (itemInfo.seller_id) {
          pureSellerId = String(itemInfo.seller_id)
          sellerId = pureSellerId
        } else {
          // 如果后端没有返回seller_id，说明可能获取失败，使用原始ID（但不会发送给Agent）
          console.warn('[OrderRecords] 后端未返回seller_id，将跳过发送chat_open命令')
        }
        
        // 更新seller_name（如果后端返回了）
        if (itemInfo.seller_name) {
          sellerName = itemInfo.seller_name
        }
        
        console.log('[OrderRecords] 已从后端获取商品信息:', {
          seller_id: pureSellerId,
          seller_name: itemInfo.seller_name,
          item_title: itemInfo.item_title,
          item_price: itemInfo.item_price,
          item_image: itemInfo.item_image,
          item_tags: itemInfo.item_tags,
          seller_avatar: itemInfo.seller_avatar
        })
      }
    } catch (e) {
      console.error('[OrderRecords] 调用openChat API失败:', e)
      // 不阻止继续，但会使用默认信息
    }
  }
  
  // ✅ 发送chat_open命令给Agent（仅用于IM连接，不再查询商品信息）
  // ⚠️ 重要：只有成功获取纯数字seller_id后才发送，避免发送加密的seller_id
  // ✅ 必须确保openChat API成功返回了纯数字seller_id
  if (chatStore.selectedClientId && itemInfo && itemInfo.seller_id) {
    // 使用后端返回的纯数字seller_id（确保是纯数字）
    const finalSellerId = String(itemInfo.seller_id)
    const isNumeric = /^\d+$/.test(finalSellerId)
    
    if (isNumeric) {
      try {
        console.log('[OrderRecords] 发送chat_open命令给Agent（仅用于IM连接）...', {
          seller_id: finalSellerId,
          item_id: itemId,
          seller_name: itemInfo.seller_name || sellerName
        })
        websocketManager.sendCommand(chatStore.selectedClientId, 'chat_open', {
          seller_id: finalSellerId, // 使用纯数字seller_id
          item_id: itemId,
          seller_name: itemInfo.seller_name || sellerName
        })
      } catch (e) {
        console.error('[OrderRecords] 发送chat_open命令失败:', e)
      }
    } else {
      console.warn('[OrderRecords] 跳过发送chat_open命令：后端返回的seller_id不是纯数字:', finalSellerId)
    }
  } else {
    console.warn('[OrderRecords] 跳过发送chat_open命令：未从后端获取到有效的商品信息或seller_id', {
      hasClientId: !!chatStore.selectedClientId,
      hasItemInfo: !!itemInfo,
      sellerId: itemInfo?.seller_id
    })
  }
  
  // ✅ 添加或更新会话（使用后端返回的商品信息）
  // ⚠️ 如果itemInfo存在，使用itemInfo.seller_id（纯数字），否则使用pureSellerId
  const finalSellerIdForSession = itemInfo?.seller_id ? String(itemInfo.seller_id) : pureSellerId
  chatStore.addOrUpdateSession({
    sellerId: finalSellerIdForSession, // 使用纯数字seller_id
    sellerName: itemInfo?.seller_name || sellerName,
    itemId: itemId,
    itemTitle: itemInfo?.item_title || itemTitle || row.item_title || null,
    itemPrice: itemInfo?.item_price || row.item_price || row.price || null,
    itemImage: itemInfo?.item_image || row.item_image || row.itemImage || row.main_pic || null,
    itemTags: itemInfo?.item_tags || row.tags || row.item_tags || [], // 使用后端返回的标签
    avatar: itemInfo?.seller_avatar || null, // 使用后端返回的头像
    lastMessage: '点击查看会话',
    lastTime: new Date().toISOString()
  })
  
  console.log('[OrderRecords] 已更新会话信息:', {
    sellerId: finalSellerIdForSession,
    sellerName: itemInfo?.seller_name || sellerName,
    itemTitle: itemInfo?.item_title,
    itemPrice: itemInfo?.item_price,
    itemImage: itemInfo?.item_image,
    itemTags: itemInfo?.item_tags,
    avatar: itemInfo?.seller_avatar
  })

  // ✅ 更新会话ID（因为seller_id可能已更新为纯数字ID）
  const updatedSessionId = `${finalSellerIdForSession}#${itemId || ''}`
  
  // 设置当前会话
  console.log('[OrderRecords] 构建的 sessionId:', updatedSessionId, 'seller_id:', finalSellerIdForSession)
  chatStore.setCurrentSession(updatedSessionId)

  // 打开聊天面板
  chatStore.setVisible(true)
  
  // ✅ 等待一小段时间让会话创建完成，然后触发会话选择
  // 这样ChatPanel会自动加载消息并选中会话
  await new Promise(resolve => setTimeout(resolve, 500))
  
  // ✅ 触发会话刷新（确保会话列表是最新的）
  // ChatPanel会监听到currentSessionId变化并自动加载消息
  console.log('[OrderRecords] 等待会话创建完成，当前会话ID:', chatStore.currentSessionId)

  ElMessage.success(`已打开与 ${sellerName} 的对话`)
}

function handleWebSocketMessage(data) {
  // ✅ 处理订单状态更新通知（包括错误信息更新）
  if (data.type === 'order_status_update') {
    const { order_id, order_status, error } = data
    if (order_status === 'cancelled') {
      ElMessage.success(`订单 ${order_id} 已成功取消`)
    } else if (error) {
      // ✅ 如果有错误信息，提示用户
      ElMessage.warning(`订单 ${order_id} 操作失败: ${error}`)
    }
    // 刷新列表以显示最新状态和错误信息
    loadOrderList()
    return
  }
  
  // 处理取消订单响应
  if (data.type === 'client_response' && data.event === 'cancel_order') {
    const { message } = data
    const { success, msg, data: resData } = message || {}
    
    if (success) {
      // 取消成功
      const orderId = resData?.order_id || resData?.orderId || ''
      ElMessage.success(orderId ? `订单 ${orderId} 已成功取消` : '订单已成功取消')
      // 刷新列表以显示最新状态
      loadOrderList()
    } else {
      // 取消失败
      ElMessage.error(msg || '订单取消失败')
      // ✅ 刷新列表以显示错误信息
      loadOrderList()
    }
  }
}

// 组件挂载时加载数据
onMounted(() => {
  console.log('[OrderRecords] 组件已挂载，开始加载数据')
  try {
    loadClientOptions()
    loadOrderList()
    
    // 注册WebSocket消息处理器
    websocketManager.on(handleWebSocketMessage)
    console.log('[OrderRecords] WebSocket消息处理器已注册')
  } catch (error) {
    console.error('[OrderRecords] 组件挂载时出错:', error)
    ElMessage.error('页面加载失败: ' + (error.message || '未知错误'))
  }
})

// 组件卸载时移除处理器
onUnmounted(() => {
  websocketManager.off(handleWebSocketMessage)
})
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.mb-4 {
  margin-bottom: 16px;
}

.mt-4 {
  margin-top: 16px;
}
</style>

